package org.budo.support.servlet.filter.origin.cross;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.budo.support.lang.util.StringUtil;

import groovy.transform.ToString;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author li
 */
@Getter
@Setter
@ToString
@Slf4j
public abstract class AbstractBudoCrossOriginFilter implements Filter {
    public static final String HTTP_METHOD_OPTIONS = "OPTIONS";

    public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";

    public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";

    public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";

    public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";

    public static final String X_DOMAIN_REQUEST_ALLOWED = "XDomainRequestAllowed";

    public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";

    private String accessControlAllowMethods = "POST, GET, OPTIONS, DELETE";

    private Integer accessControlMaxAge = 3600;

    private String accessControlAllowOrigin = "*";

    private String accessControlAllowHeaders = "*"; // X-Requested-With,Content-Type,Accept,Origin,No-Cache,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String accessControlAllowOrigin = filterConfig.getInitParameter(ACCESS_CONTROL_ALLOW_ORIGIN);
        if (!StringUtil.isEmpty(accessControlAllowOrigin)) {
            this.accessControlAllowOrigin = accessControlAllowOrigin;
        }

        String accessControlAllowHeaders = filterConfig.getInitParameter(ACCESS_CONTROL_ALLOW_HEADERS);
        if (!StringUtil.isEmpty(accessControlAllowHeaders)) {
            this.accessControlAllowHeaders = accessControlAllowHeaders;
        }

        log.warn("#44 init, accessControlAllowOrigin=" + accessControlAllowOrigin + ", accessControlAllowHeaders=" + accessControlAllowHeaders + ", filterConfig=" + filterConfig + ", this=" + this);
    }

    @Override
    public void destroy() {
        log.warn("#49 destroy, this=" + this);
    }
}